﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Hxsoft.Web.UI.WebControls;
using Hxsoft.AppV1.Module;

namespace Hxsoft.AppV1.Admin
{
	public partial class Default : BasePage
	{
		protected string UserNameClientID
		{
			get { return Login1.FindControl("UserName").ClientID; }
		}

		protected TextBox CheckCodeBox
		{
			get { return (TextBox)Login1.FindControl("TbCheckCode"); }
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				this.DataBind();

				// 确保初始化管理员用户。
				Module.SystemInit.EnsureInitUsers();
			}
		}

		protected void Login1_LoginError(object sender, EventArgs e)
		{
			Messages.Add(new PageMessage(true, null, PageMessageType.Error, "登录错误", Login1.FailureText));
		}

		protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
		{
			e.Authenticated = Users.Login(Login1.UserName, Login1.Password);
		}

		protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
		{
			args.IsValid = CheckCode.Validate(CheckCodeBox.Text);
		}

		protected void IbtLogon_Click(object sender, ImageClickEventArgs e)
		{
			if (!this.IsValid)
			{
				string errMsg = "";
				foreach (IValidator v in Validators)
				{
					if (!v.IsValid)
						errMsg += "<li>" + v.ErrorMessage + "</li>";
				}
				errMsg = "<ul>" + errMsg + "</ul>";
				Messages.Add(new PageMessage(true, null, PageMessageType.Error, "登录错误", errMsg));
			}
		}

        protected string BackUrl
        {
            get
            {
                string backUrl= Request["BackUrl"];
                if(!string.IsNullOrEmpty(backUrl))
                {
                    backUrl = backUrl.Replace("[{7}]", "&");
                }
                return backUrl;
            }
        }

        protected void Login1_LoggedIn(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(BackUrl))
            {
                Response.Redirect(BackUrl);
            }
        }
	}
}
